package com.xiaoran.robot.utils;

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;
import java.io.IOException;

public class MiraiUtils {

    private final String baseHttpUrl = YamlReader.instance.getValueByKey("mirai.baseHttpUrl").toString();
    private final String verifyKey = YamlReader.instance.getValueByKey("mirai.verifyKey").toString();
    private final String robotQQ = YamlReader.instance.getValueByKey("mirai.robotQQ").toString();

    /**
     * 得到 session
     * @return session
     */
    public String getSession(){
        String verifyUrl = baseHttpUrl + "/verify";
        String requestBody = "{ \"verifyKey\": " + verifyKey + "}";
        try {
            String rst = Jsoup.connect(verifyUrl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .requestBody(requestBody)
                    .ignoreContentType(true)
                    .post().body().text();
            Object session = JSON.parseObject(rst).get("session");
            return session.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * bind
     */
    public String bindSession(){
        String session = getSession();
        String bindUrl = baseHttpUrl + "/bind";
        String requestBody = "{\"sessionKey\": " + session + ", \"qq\": " + robotQQ + "}";
        try {
            String rst = Jsoup.connect(bindUrl).requestBody(requestBody).ignoreContentType(true)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .post().body().text();
            Object msg = JSON.parseObject(rst).get("msg");
            if("success".equals(msg.toString())){
                System.out.println("session 获取成功");
            }else {
                System.out.println("session 获取失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return session;
    }

}
